package com.cms.amp.ui.frame

import android.os.HandlerThread
import android.util.Log
import android.view.Choreographer
import android.view.FrameMetrics
import android.view.Window
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.cms.amp.R
import com.cms.amp.databinding.ActivityAmpBinding
import com.cms.amp.databinding.ActivityFrameTrackerBinding
import com.cms.amp.router.AMPRouter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.logging.Handler

@Route(path = AMPRouter.AMP_FRAME_TRACKER)
class FrameTrackerActivity : BaseActivity<ActivityFrameTrackerBinding>() {
    override fun getLayoutId(): Int = R.layout.activity_frame_tracker
    override fun initView() {

    }

    override fun initListener() {
        //android 24(7.0之前)
        addTrackerFrame()
        renderFrame()
    }

    private fun addTrackerFrame() {

        //记录上次的帧时间
        var mLastFrameTime: Long = 0
        var mFrameCount: Int = 0
        Choreographer.getInstance().postFrameCallback(object : Choreographer.FrameCallback {
            override fun doFrame(frameTimeNanos: Long) {
                //每500毫秒重新赋值一次最新的帧时间
                if (mLastFrameTime == 0L) {
                    mLastFrameTime = frameTimeNanos
                }
                //本次帧开始时间减去上次的时间除以100万，得到毫秒的差值
                val diff = (frameTimeNanos - mLastFrameTime) / 1000000.0f
                //这里是500毫秒输出一次帧率
                if (diff > 500) {
                    val fps = (mFrameCount * 1000L).toDouble() / diff
                    mFrameCount = 0
                    mLastFrameTime = 0
                    Log.d("doFrame", "doFrame: $fps")
                    mBinding.tvFps1.text = "FPS:$fps"
                } else {
                    ++mFrameCount
                }
                //注册监听下一次 vsync信号
                Choreographer.getInstance().postFrameCallback(this)
            }
        })
    }
    private fun renderFrame(){
        val handlerThread = HandlerThread("FrameMetrics")
        handlerThread.start()
        val handler = android.os.Handler(handlerThread.looper)
        window.addOnFrameMetricsAvailableListener(object :Window.OnFrameMetricsAvailableListener{
            override fun onFrameMetricsAvailable(
                window: Window?,
                frameMetrics: FrameMetrics?,
                dropCountSinceLastInvocation: Int
            ) {
                //CPU渲染到传递到GPU所用的总时间
                val metric = frameMetrics?.getMetric(FrameMetrics.TOTAL_DURATION)
              Log.i("dfsf","times:"+metric)
                GlobalScope.launch(Dispatchers.Main){
                    mBinding.tvFps2.text = "绘制一帧需要的时间:${1/ (metric!!/1000000000f)}"
                }
            }

        },handler)
    }
}